var _columns = [
    {checkbox: true},
    {title: "标识符", field: 'id'},
    {
        title: '序号', field: 'showId',
        formatter: function (value, row, index) {
            return index + 1;
        }
    },
    {field: 'indicator', title: '指标'},
    {field: 'content', title: '内容'},
    {field: 'rank', title: '等级'},
]

var formulaList = [
    {
        "indicator": "生态纺织品",
        "label1": "",
        "label2": "",
        "input1": -1,
        "input2": -1,
    },
    {
        "indicator": "产品合格率",
        "label1": "合格产品产量（１００ ｍ 布或ｔ 布）",
        "label2": "产品产量（１００ ｍ 布或ｔ 布）",
        "input1": -1,
        "input2": -1,
    },
    {
        "indicator": "原辅材料的选择",
        "label1": "",
        "label2": "",
        "input1": -1,
        "input2": -1,
    },
    {
        "indicator": "机织印染产品取水量",
        "label1": "生产取水总量 （ｔ）",
        "label2": "产品产量 （１００ ｍ 布）",
        "input1": -1,
        "input2": -1,
    },
    {
        "indicator": "针织印染产品取水量",
        "label1": "生产取水总量 （ｔ）",
        "label2": "产品产量 （ｔ 布）",
        "input1": -1,
        "input2": -1,
    },
    {
        "indicator": "机织印染产品用电量",
        "label1": "生产用电总量 （ｋＷ·ｈ）",
        "label2": "产品产量 （１００ ｍ 布）",
        "input1": -1,
        "input2": -1,
    },
    {
        "indicator": "针织印染产品用电量",
        "label1": "生产用电总量 （ｋＷ·ｈ）",
        "label2": "产品产量 （ｔ 布）",
        "input1": -1,
        "input2": -1,
    },
    {
        "indicator": "机织印染产品耗标煤量",
        "label1": "生产耗标煤量 （ｋｇ）",
        "label2": "产品产量 （１００ ｍ 布）",
        "input1": -1,
        "input2": -1,
    },
    {
        "indicator": "针织印染产品耗标煤量",
        "label1": "生产耗标煤量 （ｋｇ）",
        "label2": "产品产量 （ｔ 布）",
        "input1": -1,
        "input2": -1,
    },
    {
        "indicator": "机织印染产品废水产生量",
        "label1": "废水产生总量 （ｔ）",
        "label2": "产品产量 （１００ ｍ 布）",
        "input1": -1,
        "input2": -1,
    },
    {
        "indicator": "针织印染产品废水产生量",
        "label1": "废水产生总量 （ｔ）",
        "label2": "产品产量 （ｔ 布）",
        "input1": -1,
        "input2": -1,
    },
    {
        "indicator": "机织印染产品COD产生量",
        "label1": "ＣＯＤ 总量 （ｋｇ）",
        "label2": "产品产量 （１００ ｍ 布）",
        "input1": -1,
        "input2": -1,
    },
    {
        "indicator": "针织印染产品COD产生量",
        "label1": "ＣＯＤ 总量 （ｋｇ）",
        "label2": "产品产量 （ｔ 布）",
        "input1": -1,
        "input2": -1,
    },
]

var flag = 0;   //判断一个指标下不同等级的内容是否一样
var value1 = $('#label1').html()
var value2 = $('#label2').html()
var value3 = $('#label3').html()
var metaList;
var sub1MetaList;
var sub2MetaList;
var sub3MetaList;
var sub4MetaList;
var sub5MetaList;
var clickedButtonDOM;   //获取按钮的DOM元素
var clickedButtonId;    //获取指定的元素
var subPage = -1;
var indicator;

var TableInit = function () {
    var oTableInit = new Object();
    //初始化Table
    oTableInit.Init = function () {
        var sub1TableName = document.getElementById("sub1_table").createCaption();
        sub1TableName.innerHTML = "<b>生产工艺与装备要求</b>";
        var sub2TableName = document.getElementById("sub2_table").createCaption();
        sub2TableName.innerHTML = "<b>资源能源利用指标</b>";
        var sub3TableName = document.getElementById("sub3_table").createCaption();
        sub3TableName.innerHTML = "<b>污染物产生指标</b>";
        var sub4TableName = document.getElementById("sub4_table").createCaption();
        sub4TableName.innerHTML = "<b>产品指标</b>";
        var sub5TableName = document.getElementById("sub5_table").createCaption();
        sub5TableName.innerHTML = "<b>环境管理要求</b>";

        $('#sub1_table').bootstrapTable({
            url: '/table_clean_product/select',         //请求后台的URL（*）
            method: 'get',                      //请求方式（*）
            toolbar: '#sub1_toolbar',                //工具按钮用哪个容器
            cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
            pagination: true,                   //是否显示分页（*）
            queryParams: oTableInit.queryParams("sub1"),//传递参数（*）
            sidePagination: "client",           //分页方式：client客户端分页，server服务端分页（*）
            pageNumber: 1,                       //初始化加载第一页，默认第一页
            pageSize: 10,                       //每页的记录行数（*）
            pageList: [10, 25, 50, 100],        //可供选择的每页的行数（*）
            showColumns: true,                  //是否显示所有的列
            showRefresh: true,                  //是否显示刷新按钮
            clickToSelect: true,                //是否启用点击选中行
            uniqueId: "id",                     //每一行的唯一标识，一般为主键列
            columns: _columns,
            onPreBody: function (data) {          //在对表格体进行渲染前触发
                subPage = 1;
            }
        });

        $('#sub2_table').bootstrapTable({
            url: '/table_clean_product/select',         //请求后台的URL（*）
            method: 'get',                      //请求方式（*）
            toolbar: '#sub2_toolbar',                //工具按钮用哪个容器
            cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
            pagination: true,                   //是否显示分页（*）
            queryParams: oTableInit.queryParams("sub2"),//传递参数（*）
            sidePagination: "client",           //分页方式：client客户端分页，server服务端分页（*）
            pageNumber: 1,                       //初始化加载第一页，默认第一页
            pageSize: 10,                       //每页的记录行数（*）
            pageList: [10, 25, 50, 100],        //可供选择的每页的行数（*）
            showColumns: true,                  //是否显示所有的列
            showRefresh: true,                  //是否显示刷新按钮
            clickToSelect: true,                //是否启用点击选中行
            uniqueId: "id",                     //每一行的唯一标识，一般为主键列
            columns: _columns,
            onPreBody: function (data) {          //在对表格体进行渲染前触发
                subPage = 2;
            }
        });

        $('#sub3_table').bootstrapTable({
            url: '/table_clean_product/select',         //请求后台的URL（*）
            method: 'get',                      //请求方式（*）
            toolbar: '#sub3_toolbar',                //工具按钮用哪个容器
            cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
            pagination: true,                   //是否显示分页（*）
            queryParams: oTableInit.queryParams("sub3"),//传递参数（*）
            sidePagination: "client",           //分页方式：client客户端分页，server服务端分页（*）
            pageNumber: 1,                       //初始化加载第一页，默认第一页
            pageSize: 10,                       //每页的记录行数（*）
            pageList: [10, 25, 50, 100],        //可供选择的每页的行数（*）
            showColumns: true,                  //是否显示所有的列
            showRefresh: true,                  //是否显示刷新按钮
            clickToSelect: true,                //是否启用点击选中行
            uniqueId: "id",                     //每一行的唯一标识，一般为主键列
            columns: _columns,
            onPreBody: function (data) {          //在对表格体进行渲染前触发
                subPage = 3;
            }
        });

        $('#sub4_table').bootstrapTable({
            url: '/table_clean_product/select',         //请求后台的URL（*）
            method: 'get',                      //请求方式（*）
            toolbar: '#sub4_toolbar',                //工具按钮用哪个容器
            cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
            pagination: true,                   //是否显示分页（*）
            queryParams: oTableInit.queryParams("sub4"),//传递参数（*）
            sidePagination: "client",           //分页方式：client客户端分页，server服务端分页（*）
            pageNumber: 1,                       //初始化加载第一页，默认第一页
            pageSize: 10,                       //每页的记录行数（*）
            pageList: [10, 25, 50, 100],        //可供选择的每页的行数（*）
            showColumns: true,                  //是否显示所有的列
            showRefresh: true,                  //是否显示刷新按钮
            clickToSelect: true,                //是否启用点击选中行
            uniqueId: "id",                     //每一行的唯一标识，一般为主键列
            columns: _columns,
            onPreBody: function (data) {          //在对表格体进行渲染前触发
                subPage = 4;
            }
        });

        $('#sub5_table').bootstrapTable({
            url: '/table_clean_product/select',         //请求后台的URL（*）
            method: 'get',                      //请求方式（*）
            toolbar: '#sub5_toolbar',                //工具按钮用哪个容器
            cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
            pagination: true,                   //是否显示分页（*）
            queryParams: oTableInit.queryParams("sub5"),//传递参数（*）
            sidePagination: "client",           //分页方式：client客户端分页，server服务端分页（*）
            pageNumber: 1,                       //初始化加载第一页，默认第一页
            pageSize: 10,                       //每页的记录行数（*）
            pageList: [10, 25, 50, 100],        //可供选择的每页的行数（*）
            showColumns: true,                  //是否显示所有的列
            showRefresh: true,                  //是否显示刷新按钮
            clickToSelect: true,                //是否启用点击选中行
            uniqueId: "id",                     //每一行的唯一标识，一般为主键列
            columns: _columns,
            onPreBody: function (data) {          //在对表格体进行渲染前触发
                subPage = 5;
            }
        });
    };

    //得到查询的参数
    oTableInit.queryParams = function (page) {
        var temp = {   //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
            lastId: last_id,
            page: page
        };
        return temp;
    };
    return oTableInit;
};

var ButtonInit = function () {
    var oInit = new Object();

    oInit.Init = function () {
        //初始化页面上面的按钮事件
        // 返回按钮
        $("#btn_return").click(function () {
            $('#page-wrapper').load('pages/new_clean_product.html');
        });

        // 选择按钮
        $(".btn-select").on('click', function (event) {
            clickedButtonDOM = event.target; //获取按钮的DOM元素
            clickedButtonId = clickedButtonDOM.getAttribute('id');//获取指定的元素

            var arrselections;
            if (clickedButtonId == "sub1_select") arrselections = $("#sub1_table").bootstrapTable('getSelections');
            else if (clickedButtonId == "sub2_select") arrselections = $("#sub2_table").bootstrapTable('getSelections');
            else if (clickedButtonId == "sub3_select") arrselections = $("#sub3_table").bootstrapTable('getSelections');
            else if (clickedButtonId == "sub4_select") arrselections = $("#sub4_table").bootstrapTable('getSelections');
            else if (clickedButtonId == "sub5_select") arrselections = $("#sub5_table").bootstrapTable('getSelections');

            if (arrselections.length > 1) {
                bootoast({
                    message: '只能选择一行进行操作',
                    position: 'top',
                    type: 'warning',
                    timeout: 1.5,
                });
                return;
            } else if (arrselections.length <= 0) {
                bootoast({
                    message: '请选择有效数据',
                    position: 'top',
                    type: 'warning',
                    timeout: 1.5,
                });
                return;
            }

            indicator = arrselections[0].indicator;

            if (clickedButtonId == "sub1_select") metaList = sub1MetaList;
            else if (clickedButtonId == "sub2_select") metaList = sub2MetaList;
            else if (clickedButtonId == "sub3_select") metaList = sub3MetaList;
            else if (clickedButtonId == "sub4_select") metaList = sub4MetaList;
            else if (clickedButtonId == "sub5_select") metaList = sub5MetaList;

            if ((clickedButtonId == "sub2_select" && arrselections[0].indicator != "原辅材料的选择") || clickedButtonId == "sub3_select" || (clickedButtonId == "sub4_select" && arrselections[0].indicator.indexOf("产品合格率") != -1)) {
                var input1, input2, label1, label2;
                for (var e in formulaList) {
                    if (indicator.indexOf(formulaList[e].indicator) != -1) {
                        input1 = formulaList[e].input1;
                        input2 = formulaList[e].input2;
                        label1 = formulaList[e].label1;
                        label2 = formulaList[e].label2;
                        break;
                    }
                }

                //设置标题、标签和输入框内容
                document.getElementById("title").innerHTML = "输入数值";
                document.getElementById("input_label1").innerHTML = label1;
                document.getElementById("input_label2").innerHTML = label2;
                if (input1 != -1) {
                    $('#input1').val(input1);
                } else {
                    $('#input1').val('');
                }
                if (input2 != -1) {
                    $('#input2').val(input2);
                } else {
                    $('#input2').val('');

                }

                $('#input_modal').modal();
            } else {
                $('#select').modal();
                $('#label1').html("");
                $('#label2').html("");
                $('#label3').html("");
                var rank1Content, rank2Content, rank3Content;
                for (i = 0; i < metaList.length; i++) {
                    if (metaList[i].indicator == arrselections[0].indicator) {
                        if (metaList[i].rank == "一级") {
                            rank1Content = metaList[i].content;
                        } else if (metaList[i].rank == "二级") {
                            rank2Content = metaList[i].content;
                        } else if (metaList[i].rank == "三级") {
                            rank3Content = metaList[i].content;
                        }
                    }
                }
                //判断各个级别的内容是否相同
                flag = 0;
                //一、二级内容相同
                if (rank1Content == rank2Content) {
                    flag = 1;
                }
                //二、三级内容相同
                if (rank2Content == rank3Content) {
                    flag = 2;
                }
                //三级内容都相同
                if (rank1Content == rank2Content && rank2Content == rank3Content) {
                    flag = 3;
                }
                //各个级别内容都不相同
                if (flag == 0) {
                    $('#label1').html(value1 + rank1Content);
                    $('#label2').html(value2 + rank2Content);
                    $('#label3').html(value3 + rank3Content);
                } else if (flag == 1) {
                    $('#label1').html(value1 + rank1Content);
                    $('#label2').html(value2 + rank3Content);
                    document.getElementById("label3").style.display = "";
                } else if (flag == 2) {
                    $('#label1').html(value1 + rank1Content);
                    $('#label2').html(value2 + rank2Content);
                    document.getElementById("label3").style.display = "";
                } else if (flag == 3) {
                    $('#label1').html(value1 + rank1Content);
                    document.getElementById("label2").style.display = "";
                    document.getElementById("label3").style.display = "";
                }
            }
        });

        // 选择框内的提交
        $("#edit_data_submit").click(function () {
            var selectedRank = $('#select input:radio:checked').val();
            if (selectedRank == "") {
                alert("请选择内容和等级");
                return;
            }
            //三级内容都不同
            if (flag == 0) {
                if (selectedRank == "value1") {
                    selectedRank = "一级";
                } else if (selectedRank == "value2") {
                    selectedRank = "二级";
                } else if (selectedRank == "value3") {
                    selectedRank = "三级";
                }
                //一、二级内容相同
            } else if (flag == 1) {
                if (selectedRank == "value1") {
                    selectedRank = "一/二级";
                } else if (selectedRank == "value2") {
                    selectedRank = "三级";
                }
                //二、三级内容相同
            } else if (flag == 2) {
                if (selectedRank == "value1") {
                    selectedRank = "一级";
                } else if (selectedRank == "value2") {
                    selectedRank = "二/三级";
                }
                //三级内容都相同
            } else if (flag == 3) {
                selectedRank = "一/二/三级";
            }

            var id;
            var table;
            if (clickedButtonId == "sub1_select") {
                table = "#sub1_table";
                metaList = sub1MetaList;
            } else if (clickedButtonId == "sub2_select") {
                table = "#sub2_table";
                metaList = sub2MetaList;
            } else if (clickedButtonId == "sub3_select") {
                table = "#sub3_table";
                metaList = sub3MetaList;
            } else if (clickedButtonId == "sub4_select") {
                table = "#sub4_table";
                metaList = sub4MetaList;
            } else if (clickedButtonId == "sub5_select") {
                table = "#sub5_table";
                metaList = sub5MetaList;
            }

            var rank;
            if (selectedRank == "一/二级") {
                rank = "一级";
            } else if (selectedRank == "二/三级") {
                rank = "二级";
            } else if (selectedRank == "一/二/三级") {
                rank = "一级";
            } else {
                rank = selectedRank;
            }

            var content;
            for (var e in metaList) {
                if (metaList[e].indicator == indicator && rank == metaList[e].rank) {
                    content = metaList[e].content;
                    break;
                }
            }

            var arrselections = $(table).bootstrapTable('getSelections');
            id = arrselections[0].id;
            $(table).bootstrapTable('updateByUniqueId', {
                id: arrselections[0].id,
                row: {
                    rank: selectedRank,
                    content: content
                }
            });

            $('#select').modal('hide');
        });

        //输入框内的提交
        $("#data_submit").click(function () {
            var input1 = $('#input1').val();
            var input2 = $('#input2').val();

            if (input1 == null || input2 == null) {
                alert("输入值不能为空");
            }

            if (input2 == 0) {
                alert("分母不能为0");
                return;
            }
            var result = (input1 / input2).toFixed(3);
            var rank = '-1';

            var id;
            var table;
            if (clickedButtonId == "sub1_select") {
                table = "#sub1_table";
                metaList = sub1MetaList;
            } else if (clickedButtonId == "sub2_select") {
                table = "#sub2_table";
                metaList = sub2MetaList;
            } else if (clickedButtonId == "sub3_select") {
                table = "#sub3_table";
                metaList = sub3MetaList;
            } else if (clickedButtonId == "sub4_select") {
                table = "#sub4_table";
                metaList = sub4MetaList;
            } else if (clickedButtonId == "sub5_select") {
                table = "#sub5_table";
                metaList = sub5MetaList;
            }

            var arrselections = $(table).bootstrapTable('getSelections');
            indicator = arrselections[0].indicator;

            var level1, level2, level3;
            for (var e in metaList) {
                if (metaList[e].indicator == indicator) {
                    if (metaList[e].rank == "一级") {
                        level1 = parseFloat(metaList[e].content.split("≤")[1]);
                    } else if (metaList[e].rank == "二级") {
                        level2 = parseFloat(metaList[e].content.split("≤")[1]);
                    } else if (metaList[e].rank == "三级") {
                        level3 = parseFloat(metaList[e].content.split("≤")[1]);
                    }
                }
            }

            //产品合格率
            if (arrselections[0].indicator.indexOf("产品合格率") != -1) {
                level1 /= 100;
                level2 /= 100;
                level3 /= 100;
                if (result >= level1) {
                    rank = "一级";
                } else if (result >= level2) {
                    rank = "二级";
                } else if (result >= level3) {
                    rank = "三级";
                } else {
                    rank = '未达到三级';
                }
            } else {
                if (result <= level1) {
                    rank = "一级";
                } else if (result <= level2) {
                    rank = "二级";
                } else if (result <= level3) {
                    rank = "三级";
                } else {
                    rank = '未达到三级';
                }
            }

            id = arrselections[0].id;
            $(table).bootstrapTable('updateByUniqueId', {
                id: arrselections[0].id,
                row: {
                    rank: rank,
                    content: result
                }
            });

            //更新formulaList
            var indicator = $(table).bootstrapTable('getSelections')[0].indicator;
            for (var e in formulaList) {
                if (indicator.indexOf(formulaList[e].indicator) != -1) {
                    formulaList[e].input1 = input1;
                    formulaList[e].input2 = input2;
                    break;
                }
            }

            $('#input_modal').modal('hide');
        })

        //保存表格
        $('#save').on('click', function () {
            var flag = 1;   //五个表都成功保存，更新clean_product
            //更新sub1表
            var sub1Data = $('#sub1_table').bootstrapTable('getData', false);//获取全部数据
            var sub2Data = $('#sub2_table').bootstrapTable('getData', false);//获取全部数据
            var sub3Data = $('#sub3_table').bootstrapTable('getData', false);//获取全部数据
            var sub4Data = $('#sub4_table').bootstrapTable('getData', false);//获取全部数据
            var sub5Data = $('#sub5_table').bootstrapTable('getData', false);//获取全部数据
            var data;
            var page;

            //更新五个表格
            for (var k = 1; k <= 5; k++) {
                if (k == 1) {
                    data = sub1Data;
                    page = "sub1";
                } else if (k == 2) {
                    data = sub2Data;
                    page = "sub2";
                } else if (k == 3) {
                    data = sub3Data;
                    page = "sub3";
                } else if (k == 4) {
                    data = sub4Data;
                    page = "sub4";
                } else if (k == 5) {
                    data = sub5Data;
                    page = "sub5";
                }

                if (k == 2 || k == 3 || k == 4) {
                    var input1, input2;
                    for (var i = 0; i < data.length; i++) {
                        if (data[i].rank != null) {
                            for (var j = 0; j < formulaList.length; j++) {
                                if (data[i].indicator.indexOf(formulaList[j].indicator) != -1) {
                                    input1 = formulaList[j].input1;
                                    input2 = formulaList[j].input2;
                                    break;
                                }
                            }
                            $.ajax({
                                type: "post",
                                url: "/table_clean_product/update_include_input",
                                async: false,
                                data: {
                                    'id': data[i]['id'],
                                    'rank': data[i]['rank'],
                                    'content': data[i]['content'],
                                    'input1': input1,
                                    'input2': input2,
                                    "page": page
                                },
                                error: function () {
                                    flag = 0;   //插入失败
                                    bootoast({
                                        message: '通讯异常',
                                        position: 'top',
                                        type: 'danger',
                                        timeout: 1.5,
                                    });
                                }
                            });
                        }
                    }
                } else {
                    for (var i = 0; i < data.length; i++) {
                        if (data[i].rank != null) {
                            $.ajax({
                                type: "post",
                                url: "/table_clean_product/update",
                                async: false,
                                data: {
                                    'id': data[i]['id'],
                                    'rank': data[i]['rank'],
                                    'content': data[i]['content'],
                                    "page": page
                                },
                                error: function () {
                                    flag = 0;   //插入失败
                                    bootoast({
                                        message: '通讯异常',
                                        position: 'top',
                                        type: 'danger',
                                        timeout: 1.5,
                                    });
                                }
                            });
                        }
                    }
                }
            }

            //都成功插入,修改对应的clean_product的状态
            if (flag == 1) {
                bootoast({
                    message: '保存成功',
                    position: 'top',
                    type: 'success',
                    timeout: 2,
                });

                $.ajax({
                    type: "post",
                    url: "/table_clean_product/state_update",
                    async: false,
                    data: {
                        'id': last_id,
                        'stdState': "填写中",
                    },
                    error: function () {
                        bootoast({
                            message: '通讯异常',
                            position: 'top',
                            type: 'danger',
                            timeout: 1.5,
                        });
                    }
                });
            } else {
                alert("保存失败");
                return;
            }
        });

        //提交表格
        $('#submit').on('click', function () {
            var flag = 1;   //五个表都成功保存，更新clean_product
            //更新sub1表
            var sub1Data = $('#sub1_table').bootstrapTable('getData', false);//获取全部数据
            var sub2Data = $('#sub2_table').bootstrapTable('getData', false);//获取全部数据
            var sub3Data = $('#sub3_table').bootstrapTable('getData', false);//获取全部数据
            var sub4Data = $('#sub4_table').bootstrapTable('getData', false);//获取全部数据
            var sub5Data = $('#sub5_table').bootstrapTable('getData', false);//获取全部数据
            var data;
            var page;

            for (var k = 1; k <= 5; k++) {
                if (k == 1) data = sub1Data;
                else if (k == 2) data = sub2Data;
                else if (k == 3) data = sub3Data;
                else if (k == 4) data = sub4Data;
                else if (k == 5) data = sub5Data;

                for (var i = 0; i < data.length; i++) {
                    if (data[i].rank == null) {
                        if (k == 1) alert("生产工艺与装备要求内容不能为空！");
                        else if (k == 2) alert("资源能源利用指标内容不能为空！");
                        else if (k == 3) alert("污染物产生指标内容不能为空行！");
                        else if (k == 4) alert("产品指标内容不能为空！");
                        else if (k == 5) alert("环境管理要求内容不能为空！");
                        return;
                    }
                }
            }

            //更新五个表格
            for (var k = 1; k <= 5; k++) {
                if (k == 1) {
                    data = sub1Data;
                    page = "sub1";
                } else if (k == 2) {
                    data = sub2Data;
                    page = "sub2";
                } else if (k == 3) {
                    data = sub3Data;
                    page = "sub3";
                } else if (k == 4) {
                    data = sub4Data;
                    page = "sub4";
                } else if (k == 5) {
                    data = sub5Data;
                    page = "sub5";
                }

                if (k == 2 || k == 3 || k == 4) {
                    var input1 = -1, input2 = -1;
                    for (var i = 0; i < data.length; i++) {
                        if (data[i].rank != null) {
                            for (var j = 0; j < formulaList.length; j++) {
                                if (data[i].indicator.indexOf(formulaList[j].indicator) != -1) {
                                    input1 = formulaList[j].input1;
                                    input2 = formulaList[j].input2;
                                }
                            }
                            $.ajax({
                                type: "post",
                                url: "/table_clean_product/update_include_input",
                                async: false,
                                data: {
                                    'id': data[i]['id'],
                                    'rank': data[i]['rank'],
                                    'content': data[i]['content'],
                                    'input1': input1,
                                    'input2': input2,
                                    "page": page
                                },
                                error: function () {
                                    flag = 0;   //插入失败
                                    bootoast({
                                        message: '通讯异常',
                                        position: 'top',
                                        type: 'danger',
                                        timeout: 1.5,
                                    });
                                }
                            });
                        }
                    }
                } else {
                    for (var i = 0; i < data.length; i++) {
                        if (data[i].rank != null) {
                            $.ajax({
                                type: "post",
                                url: "/table_clean_product/update",
                                async: false,
                                data: {
                                    'id': data[i]['id'],
                                    'rank': data[i]['rank'],
                                    'content': data[i]['content'],
                                    "page": page
                                },
                                error: function () {
                                    flag = 0;   //插入失败
                                    bootoast({
                                        message: '通讯异常',
                                        position: 'top',
                                        type: 'danger',
                                        timeout: 1.5,
                                    });
                                }
                            });
                        }
                    }
                }
            }

            //都成功插入,修改对应的clean_product的状态
            if (flag == 1) {
                bootoast({
                    message: '提交成功',
                    position: 'top',
                    type: 'success',
                    timeout: 2,
                });

                $.ajax({
                    type: "post",
                    url: "/table_clean_product/state_update",
                    async: false,
                    data: {
                        'id': last_id,
                        'stdState': "已完成",
                    },
                    error: function () {
                        bootoast({
                            message: '通讯异常',
                            position: 'top',
                            type: 'danger',
                            timeout: 1.5,
                        });
                    }
                });
                $('#page-wrapper').load("pages/new_clean_product.html");
            } else {
                alert("保存失败");
                return;
            }
        });

        //取消提交表格
        $('#cancel').on('click', function () {
            //点击取消按钮，返回到上级页面，将状态改为填写中
            $.ajax({
                type: "post",
                url: "/table_clean_product/state_update",
                async: false,
                data: {
                    'id': last_id,
                    'stdState': "填写中",
                },
                success: function (data) {
                    $('#page-wrapper').load('pages/new_clean_product.html');
                },
                error: function () {
                    bootoast({
                        message: '通讯异常',
                        position: 'top',
                        type: 'danger',
                        timeout: 1.5,
                    });
                }
            });
        });
    };
    return oInit;
};

$(function () {
    //获取展示的指标
    getIndicator();

    //1.初始化Table
    var oTable = new TableInit();
    oTable.Init();

    //2.初始化Button的点击事件
    var oButtonInit = new ButtonInit();
    oButtonInit.Init();

    if (operation == 'view') {
        sub1_select.style.display = "none";
        sub2_select.style.display = "none";
        sub3_select.style.display = "none";
        sub4_select.style.display = "none";
        sub5_select.style.display = "none";
        save.style.display = "none";
        submit.style.display = "none";
        cancel.style.display = "none";

    }

    //3.隐藏列
    $('#sub1_table').bootstrapTable('hideColumn', 'id');
    $('#sub2_table').bootstrapTable('hideColumn', 'id');
    $('#sub3_table').bootstrapTable('hideColumn', 'id');
    $('#sub4_table').bootstrapTable('hideColumn', 'id');
    $('#sub5_table').bootstrapTable('hideColumn', 'id');
});

function getIndicator() {
    //查询meta_clean_product_sub1~5的数据
    for (var k = 1; k <= 5; k++) {
        $.ajax({
            url: "/table_clean_product/get_meta_data",
            async: false,
            type: "get",
            data: {
                "standardNumber": standardNumber,
                "page": "sub" + k,
            },
            success: function (result) {
                metaList = result;
                if (k == 1) sub1MetaList = result;
                else if (k == 2) sub2MetaList = result;
                else if (k == 3) sub3MetaList = result;
                else if (k == 4) sub4MetaList = result;
                else if (k == 5) sub5MetaList = result;
            },
            error: function () {
                bootoast({
                    message: '通讯异常',
                    position: 'top',
                    type: 'danger',
                    timeout: 1.5,
                });
            }
        });

        // 获得clean_product_sub*的数据
        var list;
        $.ajax({
            url: "/table_clean_product/select",
            async: false,
            type: "get",
            data: {
                "lastId": last_id,
                "page": "sub" + k,
            },
            success: function (result) {
                list = result;

                //將input插入formulaList
                if (k == 2 || k == 3 || k == 4) {
                    for (var i = 0; i < list.length; i++) {
                        for (var j = 0; j < formulaList.length; j++) {
                            if (list[i].indicator.indexOf(formulaList[j].indicator) != -1) {
                                formulaList[j].input1 = list[i].input1;
                                formulaList[j].input2 = list[i].input2;
                                break;
                            }
                        }
                    }
                }
            },
            error: function () {
                bootoast({
                    message: '通讯异常',
                    position: 'top',
                    type: 'danger',
                    timeout: 1.5,
                });
            }
        });

        for (var i = 0; i < metaList.length; i++) {
            var flag = 0;
            for (var j = 0; j < list.length; j++) {
                if (metaList[i].indicator == list[j].indicator) {
                    flag = 1;   //不用插入
                    break;
                }
            }
            //插入
            if (flag == 0) {
                list.push({"indicator": metaList[i].indicator});
                $.ajax({
                    url: "/table_clean_product/insert",
                    async: false,
                    type: "post",
                    data: {
                        "indicator": metaList[i].indicator,
                        "lastId": last_id,
                        "page": "sub" + k,
                    },
                    error: function () {
                        bootoast({
                            message: '通讯异常',
                            position: 'top',
                            type: 'danger',
                            timeout: 1.5,
                        });
                    }
                });
            }
        }
    }
}
